package com.cnc.fd.util;

import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.cnc.bas.util.Log;

public class MailSenderUtil {

    private static Log log = Log.getLogger(MailSenderUtil.class);
    
    /**
     * 发送邮件
     * @param sender  发送者
     * @param content  邮件内容
     * @param subject  主题
     * @param toAddress 邮箱地址（多个用逗号分隔）
     */
    public static void sendMail(String sender, String content, String subject,
            String toAddresses) {
        StringTokenizer st = new StringTokenizer(toAddresses, ", ");
        Set<String> set = new HashSet<String>();
        while(st.hasMoreTokens()){
            set.add(st.nextToken());            
        }
        sendMail(sender, content, subject, set.toArray(new String[set.size()]));
    }

    /**
     * 发送邮件
     * @param sender  发送者
     * @param content  邮件内容
     * @param subject  主题
     * @param toAddress 邮箱地址
     */
    public static void sendMail(String sender, String content, String subject,
            String[] toAddress) {
        Transport transport = null;
        try {

            Properties props = System.getProperties();

            props.put("mail.smtp.host", FdProperties.getProperty("SMTP_HOST"));

            props.put("mail.smtp.localhost", FdProperties
                    .getProperty("SMTP_HOST"));

            props.put("mail.smtp.auth", "true");

            Session session = Session.getDefaultInstance(props);

            MimeMessage mimeMsg = new MimeMessage(session);

            mimeMsg.setSubject(subject);

            mimeMsg.setContent(content, "text/html;charset=GBK");
             
            InternetAddress sendAddress = new InternetAddress(FdProperties.getProperty("SENDER_FROM"), sender);
            mimeMsg.setFrom(sendAddress);

            transport = session.getTransport("smtp");

            transport.connect(FdProperties.getProperty("SMTP_HOST"),
                    FdProperties.getProperty("SENDER_USER"), FdProperties
                            .getProperty("SENDER_PWD"));
            
            int sendSuccess = 0;
            for (int i = 0; i < toAddress.length; i++) {
                mimeMsg.setRecipient(Message.RecipientType.TO,
                        new InternetAddress(toAddress[i]));
                for(int j=0; j<2; j++){
                    try{
                        transport.sendMessage(mimeMsg, mimeMsg
                                .getRecipients(Message.RecipientType.TO));
                        sendSuccess ++;
                        break;
                    }
                    catch(Exception ex){
                        log.logError("send mail to " + toAddress[i] + " fail! send time[" + (j + 1 ) + "]", ex);
                    } 
                }
            }

            log.logDebug("mail send success [count: " + sendSuccess + "], failure [count:" + (toAddress.length - sendSuccess) + "], mail subject:" + subject);


        } catch (Exception e) {
            log.logError("mail send error, mail subject： " + subject, e);
        } finally {

            try {
                if (transport != null)
                    transport.close();
            } catch (Exception e) {
                // do nothing
            }
        }
    }

}
